<?php


namespace Api\Controller;

use Common\Logic\LotteryLogic;

/*
 * 抽奖控制器
 * */
class LotteryController extends BaseController
{
	public function  __construct() 
	{   
        parent::__construct();
        $header = $this->get_all_header();
        $user_id = $header['id'];
        if ($user_id) {
           $this->user_id = $user_id;
           session_start();
           $_SESSION['id'] = $this->user_id;
        }else{
            $this->user_id = 0;
        }
        
    }

    public function code(){
        $token = I('token');
        $this->assign('link',LotteryLogic::getLink($token));
        $this->display();
    }

	public function index()
	{
		if(!LotteryLogic::checkLotteryTime())
		{
			$this->error("暂无抽奖活动");
		}
		#奖品列表 
		$this->assign("prize_list",LotteryLogic::getPrizeList());
		#抽奖次数
		$this->assign("lottery_times", LotteryLogic::getUserLuckCount($this->user_id));
		#近期获奖用户  
        $this->assign("lottery_users",LotteryLogic::getLucker());
        #每天抽奖次数
        $this->assign("lotteryNum",LotteryLogic::getConfig("lotteryNum")['value']);
        #每次抽奖扣几个积分
		$this->assign("lotteryConsume",LotteryLogic::getConfig("lotteryConsume")['value']);
		$this->display();
	}

	/* 用户抽奖记录 */
    public function lottery_record()
    { 
        $this->user_id = $_SESSION['id'];

        if(IS_POST){
            try{
                $res = LotteryLogic::getUserRecord($this->user_id);

                echo json_encode([
                    "status" => "success",
                    "code" => 1,
                    "msg" => "获取成功",
                    "data" => $res
                ]);
                // var_dump($res);

            }catch(\Exception $e)
            {
                // var_dump($e);
                echo json_encode([
                    "status" => "failed",
                    "code" => $e->getCode(),
                    "msg" => $e->getMessage(),
                    "data" => ""
                ]);
            }
        }else{
            $this->display();
        }
    }


	/* 用户抽奖 */
    public function lotteryDraw()
    { 
        $this->user_id = $_SESSION['id'];
        // $this->user_id = 100;
        try{
            $res = LotteryLogic::lotteryDraw($this->user_id);
            echo json_encode([
                "status" => "success",
                "code" => 1,
                "msg" => "抽奖成功",
                "data" => $res
            ]);
            // var_dump($res);

        }catch(\Exception $e)
        {
            // var_dump($e);
            echo json_encode([
                "status" => "failed",
                "code" => $e->getCode(),
                "msg" => $e->getMessage(),
                "data" => ""
            ]);
        }
    }
}